import axios from 'axios'

var instance = axios.create({
  baseURL: 'http://localhost:3000/',
  timeout: 5000,
})

// 请求拦截器
instance.interceptors.request.use(
    function (config) {
      const token = localStorage.getItem('token')
      if (token) {
        config.headers['Authorization'] = `Bearer ${token}`
      }
      return config
    },
    function (error) {
      console.error('Request Error:', error)
      return Promise.reject(error)
    }
)

// 响应拦截器
instance.interceptors.response.use(
  function (response) {
    return response
  },
  function (error) {
    return Promise.reject(error)
  }
)

export const httpSever = ({ method = 'get', url = '', data = {}, params = {} }) => {
  return new Promise((resolve, reject) => {
    instance({
      method,
      url,
      data,
      params
    })
      .then((res) => {
        resolve(res.data)
      })
      .catch((err) => {
        reject(err)
      })
  })
}
